<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 上午10:00
 */

namespace app\common\model;

use think\Cache;
use think\Db;

/*************************************设置的KEY**************************************/

//推广海报
define("H_SETTINGS_POSTER_SPREAD", "key_spread_poster");
//用户协议
define("H_SETTINGS_TREATY", "key_treaty");
//联系我们
define("H_SETTINGS_CONTECT_US", "key_contect_us");
//关于我们
define("H_SETTINGS_ABOUT_US", "key_about_us");
//启动图片
define("H_SETTINGS_START_IMG", "key_start_img");
//全局
define("H_SETTINGS_GLOBAL", "key_global");
//幻灯
define("H_SETTINGS_SWIPER", "key_swiper");
//首页分类
define("H_SETTINGS_CATEGORY", "key_category");
//全部分类
define("H_SETTINGS_CATEGORY_ALL", "key_category_all");
class Settings extends Common
{
    /**
     * 获取指定的设置
     *
     * @param $key
     * @param $type 1 缓存存到 system_settings 2 按key单独
     * @return mixed|null
     */
    public static function getSettings($key,$type=1)
    {
        //初始化设置值
        $settings = null;

        if($type==1){
            //判断是否存在缓存
            if (Cache::store("file")->has("system_settings"))
            {
                //获取缓存
                $settingsCache = Cache::store("file")->get("system_settings");

                //判断是否存在
                if (array_key_exists($key, $settingsCache))
                {
                    $settings = $settingsCache[$key];
                }
            }
        }else{
            if (Cache::store("file")->has($key))
            {
                //获取缓存
                $settings = Cache::store("file")->get($key);
            }
        }

        //如果没有缓存
        if (is_null($settings))
        {
            //从数据库中检索数据
            $item = Db::name("system_settings")
                ->where("key_name", $key)
                ->find();

            //如果设置为空
            if (empty($item) || empty($item["value"]))
            {
                $settings = array();
            }
            else
            {
                //反串行化
                $settings = unserialize($item["value"]);

                if($type==1){
                    $settingsCache[$key] = $settings;

                    Cache::store("file")->set("system_settings", $settingsCache);
                }else{

                    Cache::store("file")->set($key, $settings);
                }
            }
        }

        return $settings;

    }

    /**
     * 设置系统设置值
     *
     * @param string $key 设置的键值
     * @param array $value 设置的数据
     * @param string $type 1 system_settings  2 存到key
     * @return bool|int|string
     */
    static public function setSettings($key, $value,$type=1)
    {
        //设置结果
        $result = false;

        //获取item
        $item = Db::name("system_settings")
            ->where("key_name", $key)
            ->find();

        //如果存在设置项，则更新值
        if ($item)
        {
            $result = Db::name("system_settings")
                ->where("key_name", $key)
                ->setField("value", serialize($value));
        }
        //否则创建设置
        else
        {
            $result = Db::name("system_settings")
                ->insert(array(
                    "key_name" => $key,
                    "value" => serialize($value),
                ));
        }

        if($type==1){
            //获取设置缓存
            $settingsCache = Cache::store("file")->has("system_settings")
                ? Cache::store("file")->get("system_settings") : array();
            //更新缓存
            $settingsCache[$key] = $value;
            Cache::store("file")->set("system_settings", $settingsCache);
        }else{
            Cache::store("file")->set($key, $value);
        }

        return $result;
    }

    /**
     *将 swiper 保存到缓存
     **/
    static public function saveSwiper(){
        $list = Db::name('swiper')->where('is_visible',1)->field('img_url,type,link_url')->order('display_order desc,id desc')->select();
        Self::setSettings(H_SETTINGS_SWIPER,$list);
    }

    /**
     *将 商城首页category 保存到缓存
     **/
    static public function saveCategory(){
        $where = [
            'is_valid'=>1,//未删除
            'is_visible'=>1,//显示
            'parent_id'=>0,//一级分类
        ];
        $list = Db::name('category')->where($where)->field('id as _id,level,title,img_url')->order('display_order desc,id desc')->limit(7)->select();
        $all = Db::name('category_all')->where('id',1)->field('title,img_url')->find();
        $all['_id'] = 0;
        $all['level'] = 0;
        array_push($list,$all);
        Self::setSettings(H_SETTINGS_CATEGORY,$list);

        $list = Db::name('category')->where($where)->field('id as _id,level,title,img_url')->order('display_order desc,id desc')->select();
        foreach ($list as &$category1)
        {
            $categoryList2 = Db::name("category")
                ->where("is_valid", 1)
                ->where('is_visible',1)
                ->where("parent_id", $category1["_id"])
                ->order("display_order DESC,id DESC")
                ->field('id as _id,level,title,img_url')
                ->select();

            //获取三级分类
            foreach ($categoryList2 as &$category2)
            {
                $categoryList3 = Db::name("category")
                    ->where("is_valid", 1)
                    ->where('is_visible',1)
                    ->where("parent_id", $category2["_id"])
                    ->order("display_order DESC,id DESC")
                    ->field('id as _id,level,title,img_url')
                    ->select();

                $category2["children"] = $categoryList3;
            }

            $category1["children"] = $categoryList2;
        }
        Self::setSettings(H_SETTINGS_CATEGORY_ALL,$list,2);
    }

    /**
     *查询 advert 保存到缓存
     * @param int $size 数量
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function getAdvert($size=3){
        $list = Db::name('advert')
            ->where('is_visible',1)
            ->field('img_url,type,link_url')
            ->order('display_order desc,id desc')
            ->limit($size)
            ->select();
        return empty($list)?array():$list;
    }
}
